﻿namespace EntityAccessImp;

public class UserServices : IUserServices
{
    public ISqlSugarClient DB { get; set; }

    public UserServices(ISqlSugarClient sqlSugarClient)
    {
        DB = sqlSugarClient;
    }

    public async Task<AddResult<int>> AddUserAsync(User user)
    {
        try
        {
            int r = await DB
                .Insertable(user)
                .ExecuteReturnIdentityAsync();
            return new AddResult<int>()
            {
                StatusCode = Code.Succeed,
                Message = "插入User成功",
                NewKey = r
            };
        }
        catch (Exception e)
        {
            return new AddResult<int>()
            {
                StatusCode = Code.DBError,
                Message = "插入User失败",
                SourceException = e
            };
        }
    }

    public async Task<DeleteResult> DeleteUserAsync(int userID)
    {
        try
        {
            int r = await DB
                .Deleteable<User>()
                .In(userID)
                .ExecuteCommandAsync();
            return new DeleteResult()
            {
                StatusCode = Code.Succeed,
                Message = "删除User成功",
                ChangedColumnNum = r
            };
        }
        catch (Exception e)
        {
            return new DeleteResult()
            {
                StatusCode = Code.DBError,
                Message = "删除User失败",
                SourceException = e
            };
        }
    }

    public async Task<GetResult<User>> GetUserAsync(int id)
    {
        try
        {
            var r = await DB
                .Queryable<User>()
                .InSingleAsync(id);
            return new GetResult<User>()
            {
                StatusCode = Code.Succeed,
                Message = "查询User成功",
                ResultObject = r
            };
        }
        catch (Exception e)
        {
            return new GetResult<User>()
            {
                StatusCode = Code.DBError,
                Message = "查询User失败",
                SourceException = e
            };
        }
    }

    public async Task<UpdateResult> UpdateUserAsync(User newUser)
    {
        try
        {
            int r = await DB
                .Updateable(newUser)
                .ExecuteCommandAsync();
            return new UpdateResult()
            {
                StatusCode = Code.Succeed,
                Message = "更新User成功",
                ChangedColumnNum = r
            };
        }
        catch (Exception e)
        {
            return new UpdateResult()
            {
                StatusCode = Code.DBError,
                Message = "更新User失败",
                SourceException = e
            };
        }
    }
}
